﻿<%@ WebHandler Language="C#" Class="RTGS.Web.ajaxhandler.rtgs.spt_record_detail_i" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using RTGS.Library.Enum;
using RTGS.Library.DataAccess.Rtgs;
using RTGS.Library.Entities.Rtgs;
using RTGS.Web.support;
using System.Configuration;
using RTGS.Library.DataAccess.UserManagement;
using RTGS.Library.Entities.UserManagement;
namespace RTGS.Web.ajaxhandler.rtgs
{
   public class spt_record_detail_i : BaseHandler
    {
       private stpRecordDetailIRepo stpRecordDal = new stpRecordDetailIRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);

       private sysTLogRepo logDal = new sysTLogRepo(ConfigurationManager.ConnectionStrings["Rtgs"].ConnectionString);
       private sysTLog log = new sysTLog();
       
        private string MethodName = string.Empty;
        private string typeIncoming = string.Empty;

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];
            if (context.Request.Params["typeIncoming"] != null)
                typeIncoming = context.Request.Params["typeIncoming"];

            context.Response.Clear();
            context.Response.Buffer = true;

            switch (MethodName.ToLower())
            {
                case ("update"):
                    context.Response.Write(Update(context));
                    break;
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                default:
                    // do nothing
                    break;
            }

            context.Response.Flush();
            context.Response.End();

        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region CRUD Handler

        private string Update(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            stpRecordDetailI obj = new stpRecordDetailI();

            ////GROUP TRN
            //obj.recordDetailItrTrn = context.Request.Params["trn"];
            //obj.recordDetailItrRelatedtrn = context.Request.Params["relatedTrn"];

            ////GROUP AMOUNT
            //obj.recordDetailItrAmount = context.Request.Params["amount"];
            //obj.recordDetailIstCurrency = context.Request.Params["currency"];
            //obj.recordDetailItrValuedate = context.Request.Params["bussinesDay"];

            ////GROUP DEBIT PARTICIPANT
            //obj.recordDetailIstFromaccountnumber = context.Request.Params["debitParticipant"];
            //obj.recordDetailIstFromaccountname = context.Request.Params["accountDebitParticipant"];


            ////GROUP CREDIT PARTICIPANT
            //obj.recordDetailIstToaccountnumber = context.Request.Params["creditParticipant"];
            //obj.recordDetailIstToaccountname= context.Request.Params["accountCreditParticipant"];


            ////GROUP DEBIT PARTICIPANTS CLIENT
            //obj.recordDetailIstOriginatingname = context.Request.Params["debitParticipantsClient"];
            //obj.recordDetailIstOriginatingnumber = context.Request.Params["accountDebitParticipantsClient"];


            ////GROUP CREDIT PARTICIPANTS CLIENT
            //obj.recordDetailIstUltimatebenefname = context.Request.Params["creditParticipantsClient"];
            //obj.recordDetailIstUltimatebenefaccount = context.Request.Params["accountParticipantsClient"];

            ////GROUP DETAIL
            //obj.recordDetailIstMemberinfo = context.Request.Params["remitanceInformation"];
            //obj.recordDetailItrRecordtype = context.Request.Params["detailOfCharges"];
            //obj.recordDetailItrTransactioncode = context.Request.Params["transactionSubTypeCode"];
            //obj.recordDetailIstPaymentdetails = context.Request.Params["sender"];


            ////GROUP PRIORITY

            //obj.recordDetailIrecordSwiftIdatetime = DateTime.Now;
            //obj.recordDetailIrecordtime= DateTime.Now;


            obj.recordDetailItrRelatedtrn = context.Request.Params["Id"];

            if (context.Request.Params["typeIncoming"].ToString().Trim().Contains("repair"))
            {
                obj.recordDetailIstStatus = "CP";

                if (context.Request.Params["reasoncode"].ToString() == "011")
                {
                    //if (context.Request.Params["bussinesDay"] != null && context.Request.Params["bussinesDay"].ToString().Trim() != "")
                    //{
                    //    if (context.Request.Params["bussinesDay"].ToString().Trim().Contains("/"))
                    //    {
                    //        //obj.recordDetailOtrValuedate = Convert.ToDateTime(context.Request.Params["bussinesDay"]).ToString("yyyyMMdd");

                    //        string[] splitTanggal = context.Request.Params["bussinesDay"].ToString().Trim().Split('/');

                    //        obj.recordDetailItrValuedate = splitTanggal[2].ToString() + splitTanggal[1].ToString() + splitTanggal[0].ToString();
                    //    }
                    //    else
                    //    {
                    //        obj.recordDetailItrValuedate = context.Request.Params["bussinesDay"].ToString();
                    //    }

                    //}
                    
                    if(context.Request.Params["creditParticipantsClient"].ToString().Trim().Length>140)
                        obj.recordDetailIstUltimatebenefname =context.Request.Params["creditParticipantsClient"].ToString().Substring(0,140);
                    else
                        obj.recordDetailIstUltimatebenefname = context.Request.Params["creditParticipantsClient"].ToString();

                    obj.recordDetailIstUltimatebenefaccount = context.Request.Params["accountParticipantsClient"];
                        
                        
                }

                if (context.Request.Params["reasoncode"].ToString() == "012")
                {
                    //obj.recordDetailIstToaccountname = context.Request.Params["debitParticipant"];
                    //obj.recordDetailIstToaccountnumber = context.Request.Params["accountDebitParticipant"];
                    //obj.recordDetailItrTomember = context.Request.Params["memberCodeDebit"];

                    //obj.recordDetailIstFromaccountname = context.Request.Params["creditParticipant"];
                    //obj.recordDetailIstFromaccountnumber = context.Request.Params["accountCreditParticipant"];
                    //obj.recordDetailItrFrommember = context.Request.Params["memberCodeCredit"];

                    if (context.Request.Params["debitParticipantsClient"].ToString().Trim().Length > 140)
                        obj.recordDetailIstOriginatingname = context.Request.Params["debitParticipantsClient"].ToString().Substring(0, 140);
                    else
                        obj.recordDetailIstOriginatingname = context.Request.Params["debitParticipantsClient"].ToString();
                    
                    obj.recordDetailIstOriginatingnumber = context.Request.Params["accountDebitParticipantsClient"];
                }

                //if (context.Request.Params["reasoncode"].ToString() == "004")
                //    obj.recordDetailItrAmount = context.Request.Params["amount"];
            }

            if (context.Request.Params["typeIncoming"].ToString().Trim().Contains("drop"))
            {
                obj.recordDetailIstStatus = "DO";
            }

            if (context.Request.Params["typeIncoming"].ToString().Trim().Contains("accept"))
            {
                obj.recordDetailIstStatus = "WA";
            }



            if (stpRecordDal.UpdateByStatus(obj, typeIncoming, context.Request.Params["reasoncode"].ToString().Trim()))
            {
                helper.Data = obj;
                helper.Message = "Data has been saved!";
                helper.IsSuccess = true;

                log = new sysTLog();
                log.logEvent = "Update STP_RECORD_DETAIL_I " + typeIncoming + "  Success";
                log.logMessage = string.Empty;
            }
            else
            {
                helper.IsSuccess = false;
                helper.Message = stpRecordDal.GetErrorMessage();

                log = new sysTLog();
                log.logEvent = "Update STP_RECORD_DETAIL_I " + typeIncoming + "  Error";
                log.logMessage = string.Empty;

            }

            log.logSource = "spt_record_detail_i.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log);

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }




        private string GetData(HttpContext context)
        {
            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);
            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);
            string sidx = ((context.Request.QueryString["sidx"]) == null ? stpRecordDetailI.Fields.recordDetailItrRelatedtrn : context.Request.QueryString["sidx"].ToString());
            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());
            string parameters = string.Empty;
            if (typeIncoming.Trim().ToLower() == "accept")
                parameters = parameters.Trim().Length > 0 ? parameters + " AND UPPER(RECORD_DETAIL_IST_Status) = 'CP' " : " WHERE UPPER(RECORD_DETAIL_IST_Status) = 'CP'";
            if (typeIncoming.Trim().ToLower() == "drop")
                parameters = parameters.Trim().Length > 0 ? parameters + " AND UPPER(RECORD_DETAIL_IST_Status) IN ('RF','CP') " : " WHERE UPPER(RECORD_DETAIL_IST_Status) IN ('RF','CP')";
            if (typeIncoming.Trim().ToLower() == "repair")
                parameters = parameters.Trim().Length > 0 ? parameters + " AND UPPER(RECORD_DETAIL_IST_Status) = 'RF' " : " WHERE UPPER(RECORD_DETAIL_IST_Status) = 'RF'";
            string valuedate = ((context.Request.Params["valuedate"]) == null ? string.Empty : context.Request.QueryString["valuedate"].ToString());
            string trn = ((context.Request.Params["trn"]) == null ? string.Empty : context.Request.QueryString["trn"].ToString());
            string batchref = ((context.Request.Params["batchref"]) == null ? string.Empty : context.Request.QueryString["batchref"].ToString());
            string status = ((context.Request.Params["status"]) == null ? string.Empty : context.Request.QueryString["status"].ToString());
            string refno = ((context.Request.Params["refno"]) == null ? string.Empty : context.Request.QueryString["refno"].ToString());
            string tomember = ((context.Request.Params["tomember"]) == null ? string.Empty : context.Request.QueryString["tomember"].ToString());


            parameters = !string.IsNullOrEmpty(valuedate) ?
                   (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_OTR_ValueDate LIKE '%" + valuedate + "%'" : " WHERE RECORD_DETAIL_OTR_ValueDate LIKE '%" + valuedate + "%'")
                                 : parameters;

            parameters = !string.IsNullOrEmpty(trn) ?
                   (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_OTR_TRN LIKE '%" + trn + "%'" : " WHERE RECORD_DETAIL_OTR_TRN LIKE '%" + trn + "%'")
                                 : parameters;

            parameters = !string.IsNullOrEmpty(batchref) ?
                   (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_ORECORD_OH_BatchReference LIKE '%" + batchref + "%'" : " WHERE RECORD_DETAIL_ORECORD_OH_BatchReference LIKE '%" + batchref + "%'")
                                 : parameters;


            parameters = !string.IsNullOrEmpty(status) ?
                   (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_ORECORD_Status LIKE '%" + status + "%'" : " WHERE RECORD_DETAIL_ORECORD_Status LIKE '%" + status + "%'")
                                 : parameters;

            parameters = !string.IsNullOrEmpty(refno) ?
                   (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_ORECORD_RefNo LIKE '%" + status + "%'" : " WHERE RECORD_DETAIL_ORECORD_RefNo LIKE '%" + refno + "%'")
                                 : parameters;

            parameters = !string.IsNullOrEmpty(tomember) ?
                   (!string.IsNullOrEmpty(parameters) ? parameters + " AND RECORD_DETAIL_OTR_ToMember LIKE '%" + tomember + "%'" : " WHERE RECORD_DETAIL_OTR_ToMember LIKE '%" + tomember + "%'")
                                 : parameters;

            int totalCount = Convert.ToInt32(stpRecordDal.SelectScalar(SQL.Function.Aggregate.Count, stpRecordDetailI.Fields.recordDetailItrRelatedtrn, parameters));
            decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
            int totalPages = Convert.ToInt32(dc);
            List<stpRecordDetailI> pagedList = stpRecordDal.GetList(pageSize, page, sidx, sord, parameters);
            if (!string.IsNullOrEmpty(stpRecordDal.GetErrorMessage()))
            {

                log = new sysTLog();
                log.logEvent = "GetData STP_RECORD_DETAIL_I " + typeIncoming + "  Success";
                log.logMessage = string.Empty;

            }
            else
            {
                log = new sysTLog();
                log.logEvent = "View Data STP_RECORD_DETAIL_I " + typeIncoming + "  Error";
                log.logMessage = string.Empty;
            }

            log.logSource = "stp_record_detail_i.ashx";
            log.createdBy = base.UserLoggedIn;
            log.createdDate = DateTime.Now;
            logDal.Save(log);
            
            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,

            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
        }

        #endregion


    }
}
